/**
* @Title: selfFeedback_ctrl.js
* @Description: TODO
* Copyright: Copyright (c) 2014 
 * Company:中国平安
*
* @Project HIMS-FWA
* @date 2014年11月13日 下午10:20:38
* @version V1.0
*/
;
(function(){
	'use strict';
	
	var app = angular.module('fwa.mainApp');
	app.controller('SelfFeedbackEditCtrl', ['$scope','$upload','$http','$modal','$stateParams','CaseCommonService','$state','BaseURL','Modal','SelfFeedbackService','CommunityService',
	                                function($scope,$upload,$http,$modal,$stateParams,CaseCommonService,$state,baseUrl,Modal,SelfFeedbackService,CommunityService){
		$scope.communityService = CommunityService;
		
		$scope.selfFeedbackService = SelfFeedbackService;
		var warnNo=	$stateParams.warnNo;
		$scope.columns = [
		                  {
			                   label: '省科室',
							   map: 'deptName',
							   width: '15%'
						  }, {
							   label: '费用类型',
							   map : 'warnfeeType',
							   width : '20%'
						  }, {
							   label: '费用金额(元)',
							   map: 'feeAmount',
							   width: '21%'
						  }, {
							   label: '医院科室',
							   map: 'orgDepName',
							   width: '17%'							   
						  }, {
							   label: '概要',
							   map: 'warnReason',
							   width: '27%'
						  }
						 ];
		
		
		
		var params = {
						orgId:"2",
						warnNo:warnNo
					 };		
		
		$scope.tableData = [];
		//获取通知单信息
		SelfFeedbackService.getSelfFeedbackDetail(params).success(function(res){
			//$scope.selfFeedback = res.selfFeedback;
			$scope.selfFeedback={};
			//$scope.selfFeedback.requisitionNo=warnNo;
			//$scope.selfFeedback.areaName="厦门市";
			angular.forEach(res.notice,function(data,index){				
				if (data.docKey =="name") {
					$scope.selfFeedback.orgName=data.docValue1;
				}
				if (data.docKey =="content") {
					$scope.selfFeedback.reason=data.docValue1;
				}
				if (data.docKey =="dateend") {
					$scope.selfFeedback.endWarningDate=data.docValue1;
				}
				if (data.docKey =="datestart") {
					$scope.selfFeedback.startWarningDate=data.docValue1;
				}
				if (data.docKey =="requirement") {
					$scope.selfFeedback.demand=data.docValue1;
				}
				if (data.docKey =="regionName") {
					$scope.selfFeedback.areaName=data.docValue1;
				}
				if (data.docKey =="noticeNo") {
					$scope.selfFeedback.noticeNo=data.docValue1;
				}				
			});
			$scope.selfFeedback.WarningDate=SelfFeedbackService.setPriodDate($scope.selfFeedback.startWarningDate,$scope.selfFeedback.endWarningDate);
			if(res.feedback){
				$scope.selfFeedback.requisitionNo=res.feedback.warnNoBiz;
			if(res.feedback.checkSituation)
			$scope.selfFeedback.check=res.feedback.checkSituation;//自查情况
			if(res.feedback.checkMeasure)
			$scope.selfFeedback.corrective=res.feedback.checkMeasure;//整改措施
			}
			if(res.feedbackDetail){
				$scope.tableData = res.feedbackDetail;
			}
			
			calAmount();
			 imageList();
		});
		

		//弹窗
		$scope.openModal = function(){
			var warnDatas = $scope.warnDatas;
			 var modalInstance = $modal.open({
			      templateUrl:'resultAdd_view.html',
			      backdrop:'static',
				  size:'sm',
				  controller: function($scope, $modalInstance,Modal,CommunityService){
					  $scope.communityService = CommunityService;
					  CommunityService.initCodeListDatas();					  
					  $scope.form = {};
					  $scope.medicalOrgDeptList = [];
					  $scope.provincialOrgDepList = [];
					  CommunityService.getProvincialOrgDepList({warnNo:$stateParams.warnNo})
					  .success(function(response, status, headers, config){
						  $scope.provincialOrgDepList = response.list || [];
						});
					  //关闭弹窗
					  $scope.onOk = function() {
						  $modalInstance.dismiss();
					  }
					//监听省科室值变化
						$scope.$watch('form.deptCode',function(v){
							if (v) {
								// 获取医院科室  参数 departMent：省科室
								CommunityService.getMedicalOrgCodeListDatas(
										{warnNo:$stateParams.warnNo,departMent:$scope.form.deptCode})
										.success(function(response){
									$scope.medicalOrgDeptList = response.list || [];
								});
							}
							else {
								$scope.medicalOrgDeptList = [];
							}
						});
					  //确定事件
					  $scope.confirm = function() {
						if(!$scope.form.deptCode){
							Modal.alert("请选中一项省科室!!!");
							return false;
						}
						if(!$scope.form.warnfeeTypeCode){
							Modal.alert("请选中一项费用类型!!!");
							return false;
						}
						//var canonical = /^(([1-9][0-9]*\.[0-9]{2})|([0]\.[0-9]{2}))$/;
						var canonical =/^\d+(\.\d{1,2})?$/;
						if(!canonical.test($scope.form.feeAmount)){
							Modal.alert("费用金额必须是数字(最多两位小数)!!!");
							return false;
						}
						if(!$scope.form.orgDepCode){//orgDepName
							Modal.alert("请输入医院科室!!!");
							return false;
						}else{
							angular.forEach($scope.medicalOrgDeptList,function(data,index){
								if ($scope.form.orgDepCode === data.workDepCode) {
									$scope.form.orgDepName = data.workDep;//医院科室
								}
							});
						}
						if($scope.form.warnfeeTypeCode=='05'&&!$scope.form.warnReason){
							Modal.alert("请输入概要!!!");
							return false;
						}
						$scope.form.warnNo = warnNo;
						angular.forEach($scope.communityService.provincialDepDatas,function(data,index){
							if ($scope.form.deptCode === data.code) {
								$scope.form.deptName = data.name;//省科室
							}
						});
						angular.forEach($scope.communityService.warnReasonDatas,function(data,index){
							if ($scope.form.warnfeeTypeCode === data.code) {
								$scope.form.warnfeeType = data.name;
							}						
						});
						$scope.form.feeAmount =parseFloat($scope.form.feeAmount).toFixed(2);//金额保留两位小数 	
						$modalInstance.close($scope.form);
					  }
				  }
			 });
			 modalInstance.result.then(function(item) {
        		if (item) {
        			$scope.tableData.push(item);
        			calAmount();
        		}
        		
    	    });
		}
		$scope.feeAmountCount = "0.00";
		
		calAmount();
		
		//计算合计金额
		function calAmount() {
			var countNum = 0;
			angular.forEach($scope.tableData,function(data,index){
				countNum = countNum + parseFloat(data.feeAmount) * 100;
			});
			$scope.feeAmountCount = (countNum/100).toFixed(2);
		}
		
		
        //删除选中的值
		$scope.delTabaleData = function() {
			var tabaleDatas = [];
			angular.forEach($scope.tableData,function(data,index) {
				if(data.checked != true){
					tabaleDatas.push(data);
				}
			});
			$scope.tableData = tabaleDatas;
			calAmount();
		}
		
		//提交医院自查反馈
		$scope.saveSelfFeedback = function() {
			
			if (!$scope.selfFeedback.check) {
				Modal.alert("自查情况不能为空!!!");
				return false;
			}
			if (!$scope.selfFeedback.corrective) {
				Modal.alert("整改措施不能为空!!!");
				return false;
			}
			
			if (!$scope.tableData 
				|| $scope.tableData.length <= 0) {
				Modal.alert("自查结果统计不能为空!!!");
				return false;
			}			
			var data = {
					    warnNo:warnNo,
						check: $scope.selfFeedback.check,
						corrective: $scope.selfFeedback.corrective,
						resultsStatistical: $scope.tableData,
						feeAmountCount:$scope.feeAmountCount
					    };			
			SelfFeedbackService.loading = true;			
			SelfFeedbackService.saveSelfFeedback(data).success(function(res){
				Modal.alert(res.msg);
				SelfFeedbackService.loading = false;
				$state.go("selfFeedback.selfFeedbackList");
			});
			
		}
		//返回列表页面
		$scope.backSelfFeedback = function(){
        	$state.go("selfFeedback.selfFeedbackList");
        }
		
		//通知单下载
		$scope.downFile=function(){
			var scope = $scope.$new();
				var modalInstance = $modal.open({
		      	      templateUrl: baseUrl +'views/hcpms/warning/warnView/warningViewNotice_view.html',
		      	      backdrop:'static',
					  size:'sm',
					  scope:scope,
		      	      controller:function($modalInstance,$scope){
		      	    	 $scope.$watch('$viewContentLoaded',function(){
		      	    		 openFile('03','warningViewNoticeOpenpdf');
			      	      });
		      	    	  $scope.onOk = function(){
					  		   $modalInstance.dismiss();
					  	   }	
					  }
		  	    });
  	         
		}
		
		
		/**打开PDF文件*/
		   function openFile(param,openpdfId){
		   			var success = new PDFObject({ url:baseUrl+'HcpmsWarnDownFile/downPdfFile.do?warnNo='+warnNo+'&docType='+param,
		   				pdfOpenParams: { navpanes: 1,
		                 toolbar: 1,
		                 statusbar: 1,
		                 view: 'FitV',
		                 pagemode: 'thumbs'
		   			}}).embed(openpdfId);
		   }
		
		/**
         * 文件批量删除
         */
        $scope.deleteFile=function(id)
        {
                var  params= {
                    id : "'"+id+"'"
                };
                Modal.confirm('确认删除吗？',function() {
                    $http.post(baseUrl + 'common/deleteFile.do', params).success(function (data) {
                        if (data.state == '0') {
                            Modal.alert("文件删除成功！");
                        } else {
                            Modal.alert("删除失败！");
                        }
                        imageList();
                    })
                })

        }
		
		
		
		/**
         * 文件上传
         */
        $scope.files=[];
        var fileTypes = ['jpg', 'jpeg', 'png', 'bmp', 'gif', 'txt', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx','pdf', 'csv', 'rar', 'zip','7z', 'cab', 'iso'];
        $scope.uploadFile = function(){
            
            if($scope.files.length>0)
            {
                for(var i = 0; i < $scope.files.length; i++){
                    var file = $scope.files[i];
                    var fileName = file.name;
                    var fileNameArray = fileName.split(".");
                    var fileType = fileNameArray[fileNameArray.length - 1];

                    if(!isBelongToFileTypes(fileTypes, fileType)){
                    	Modal.alert("文件格式只支持(jpg、jpeg、bmp、gif、png、txt、doc、docx、xls、xlsx、ppt、pptx、pdf、csv、rar、zip、7z、cab、iso)");
                        return;
                    }
                    if(file.size > 2097152){
                        Modal.alert(fileName + "的大小不能超过2M！");
                        return;
                    }
                }
                //防止处理时间过长重复提交，提交按钮禁用
                $scope.isDisabled=true;
                $upload.upload({
                    url : baseUrl + 'common/fileInfoCreate.do',
                    params : {
                        id : warnNo,
                        imageType : '04'
                    },
                    file : $scope.files
                }).success(function(data) {
                    $scope.isDisabled=false;
                    if(data.state=='0')
                    {
                        Modal.alert(data.msg);
                        $scope.files = [];
                    }else
                    {
                        Modal.alert("附件上传失败！");
                    }
                    imageList();
                });
            }else
            {
                Modal.alert("请选择需上传的附件！");
            }
        }
        
        
        //判断文件类型
        function isBelongToFileTypes(fileTypes, fileType)
        {
            for(var i = 0; i < fileTypes.length; i++)
            {
                var tmpFileType = fileTypes[i];
                if(tmpFileType == fileType.toLocaleLowerCase())
                {
                    return true;
                }
            }
            return false;
        }
		
        //鼠标移动事件
        $scope.showId = "";
        $scope.mouseover=function(id)
        {
            $scope.showId = id;
        }

        
        //获取附件信息
        $scope.path="";
        $scope.fileDatas=[];
        function imageList()
        {
        	 var params = {id:warnNo};
            CaseCommonService.showImage(params).success(function(res){
                $scope.fileDatas=res.result.imgList;
                $scope.path=res.path;
            });
        }
        
        
        /**
         * 查看文件
         */
        $scope.openLoadFile=function(item){
            var path= $scope.path+'/'+item.businessNo+'/insurance/'+ item.name;
           var  param={filePath:path};
            $http.post(baseUrl + 'common/exitFile.do',param).success(function(data) {
                if(data.state!="error")
                {
                    window.open(baseUrl + '/file/openPdfFile.do?filePath='+path);
                }else
                {
                    Modal.alert(data.msg);
                }
            })
        }
        
        /**
         * 下载文件
         */
        $scope.downLoadFile=function(item){
            var path="";
            var suffix = item.name.substring(0,item.name.lastIndexOf('.'));
            window.location = baseUrl + 'common/downloadFile.do?fileInfoId='+item.businessNo+'/insurance/'+suffix+
                '&fileName='+item.name+'&path='+path;
        }
        
	}]);
})();